#include "stdafx.h"
#include "CListControl.h"



CListControl::CListControl()
	: m_bSuspendLayerout(false), m_bLayerouted(true), m_eHightLightType(ListControlHightLightTypeItem),
	m_iSelectedIndex(-1), m_eSelectMode(SelecteModeSingle)
{

}
CListControl::CListControl(int_32 iX, int_32 iY, int_32 iWidth, int_32 iHeight)
	: CControl(iX, iY, iWidth, iHeight), m_bSuspendLayerout(false), m_bLayerouted(true), 
	m_eHightLightType(ListControlHightLightTypeItem), m_iSelectedIndex(-1), m_eSelectMode(SelecteModeSingle)
{

}
CListControl::~CListControl()
{

}

void CListControl::AddItem(const CTextW & text, void * pUserData/* = nullptr*/)
{
	m_arrItems.Add(CListItem(text, pUserData));
	m_bLayerouted = false;
	if(!m_bSuspendLayerout)
		PerformLayerout();
}

const ListItemArray & CListControl::GetItemArray() const
{
	return m_arrItems;
}

void CListControl::SetSelect(int iIndex, bool bSelected/* = true*/)
{
	if(iIndex < -1 || iIndex >= m_arrItems.GetLength())
		iIndex = -1;

	if(m_eSelectMode == SelecteModeSingle)
	{
		if(bSelected)
		{
			if(iIndex != m_iSelectedIndex)
			{
				int_32 iSelectedIndex = m_iSelectedIndex;
				m_iSelectedIndex = iIndex;
				if(iSelectedIndex != -1)
				{
					CListItem & item = m_arrItems[iSelectedIndex];
					item.IsSelected = false;
					SelectItem(iSelectedIndex, false);
				}

				if(iIndex != -1)
				{
					CListItem & item = m_arrItems[iIndex];
					item.IsSelected = true;
					SelectItem(iIndex, false);
				}
			}
			else {}
		}
	}
	else {}
}

void CListControl::DrawItems(IPaint * pPaint) const
{
	int_32 iY = 0;
	CSolidBrush brush(m_uiForeColor);
	for(int_x cnt = 0, size = m_arrItems.GetLength(); cnt != size; ++cnt)
	{
		const CListItem & item = m_arrItems[cnt];
		pPaint->DrawString(item.Text, item.Text.GetLength(), 0, iY, &brush);
		iY += item.Height;
	}
}

void CListControl::SuspendLayerout()
{
	m_bSuspendLayerout = true;
}
void CListControl::ResumeLayerout()
{
	m_bSuspendLayerout = false;
	if(!m_bLayerouted)
		PerformLayerout();
}
bool CListControl::IsLayeroutSuspended() const
{
	return m_bSuspendLayerout;
}

void CListControl::PerformLayerout()
{
	ITextEngine * pTextEngine = GetTextEngine();
	CSizeInt32 siText;
	for(int_x cnt = 0, size = m_arrItems.GetLength(); cnt != size; ++cnt)
	{
		CListItem & item = m_arrItems[cnt];
		if(!item.IsValid)
		{
			pTextEngine->MeasureString(item.Text, item.Text.GetLength(), m_fontFormat, siText);
			item.Width = siText.Width;
			item.Height = siText.Height;
			item.IsValid = true;
		}
	}
	m_bLayerouted = false;
	Repaint();
}

void CListControl::SetHightLightType(ListControlHightLightType eHightLightType)
{
	if(eHightLightType != m_eHightLightType)
	{
		m_eHightLightType = eHightLightType;
		Repaint();
	}
}
